<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>书籍下载器</title>
    <!-- Bootstrap 5 样式 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- FontAwesome 图标 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: #f5f7fa;
        }
        .container {
            margin-top: 80px;
            max-width: 700px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        #logBox {
            height: 200px;
            overflow-y: auto;
            background: #000;
            color: #0f0;
            font-family: monospace;
            padding: 10px;
            border-radius: 8px;
        }
    </style>
</head> 
<body>
<div class="container">
    <div class="card p-4">
        <h3 class="mb-4 text-center"><i class="fa-solid fa-book"></i> 在线书籍下载器</h3>

        <!-- 输入 URL -->
        <div class="mb-3">
            <label for="urlInput" class="form-label">请输入书籍页面 URL</label>
            <input type="text" class="form-control" id="urlInput" placeholder="">
        </div>

        <!-- 开始按钮 -->
        <div class="d-grid mb-3">
            <button id="startBtn" class="btn btn-primary">
                <i class="fa-solid fa-download"></i> 开始解析并下载
            </button>
        </div>

        <!-- 下载进度条 -->
        <div class="mb-3">
            <label class="form-label">下载进度</label>
            <div class="progress">
                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated"
                     role="progressbar" style="width: 0%">0%</div>
            </div>
        </div>

        <!-- 日志输出 -->
        <div>
            <label class="form-label">下载日志</label>
            <div id="logBox"></div>
        </div>
    </div>
</div>

<!-- 高级预览模态框 -->
<div class="modal fade" id="previewModal" tabindex="-1" aria-hidden="true" style="width: 1400px">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content" style="border-radius: 15px; overflow: hidden; background: linear-gradient(145deg, #ffffff, #e0e7ff); box-shadow: 0 10px 30px rgba(0,0,0,0.2);">

            <div class="modal-header border-0">
                <h5 class="modal-title text-primary"><i class="fa-solid fa-book-open-reader"></i> 下载预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>

            <div class="modal-body p-4">
                <div class="row">
                    <!-- 左边封面 -->
                    <div class="col-md-4 text-center mb-3 mb-md-0">
                        <img id="previewCover" src="" alt="封面预览" class="img-fluid rounded shadow-sm" style="max-height: 220px;">
                    </div>

                    <!-- 右边信息 -->
                    <div class="col-md-8">
                        <ul class="list-group list-group-flush">
<!--                            <li class="list-group-item"><strong>书名:</strong> <span id="previewTitle"></span></li>-->
                            <!-- 书名可编辑 -->
                            <li class="list-group-item">
                                <strong>书名:</strong>
                                <input type="text" id="previewTitleInput" class="form-control form-control-sm d-inline-block"
                                       style="width: 100%;" />
                            </li>
                            <li class="list-group-item"><strong>图片前缀 URL:</strong> <span id="previewImageUrl"></span></li>
                            <li class="list-group-item"><strong>起始页:</strong> <span id="previewBeginPage"></span></li>
                            <li class="list-group-item"><strong>结束页:</strong> <span id="previewEndPage"></span></li>
                            <li class="list-group-item"><strong>图片类型:</strong> <span id="previewPictureType"></span></li>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="modal-footer border-0">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" id="confirmDownloadBtn" class="btn btn-primary"><i class="fa-solid fa-download"></i> 开始下载</button>
            </div>

        </div>
    </div>
</div>


<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    const startBtn = document.getElementById("startBtn");
    const urlInput = document.getElementById("urlInput");
    const logBox = document.getElementById("logBox");
    const progressBar = document.getElementById("progressBar");

    function logMessage(msg) {
        logBox.innerHTML += msg + "<br/>";
        logBox.scrollTop = logBox.scrollHeight;
    }

    function updateProgress(percent) {
        progressBar.style.width = percent + "%";
        progressBar.textContent = percent + "%";
    }

    startBtn.addEventListener("click", async () => {
        const url = urlInput.value.trim();
        if (!url) {
            alert("请输入 URL！");
            return;
        }

        logBox.innerHTML = "";
        updateProgress(0);
        logMessage("开始解析: " + url);

        try {
            // Step1: 请求后端解析页面，返回 DownloadBooks 参数
            let parseResp = await axios.get("/api/parse", { params: { url: url } });
            let downloadBooks = parseResp.data;

            logMessage("解析成功，显示预览...");

            // Step2: 填充模态框内容
            document.getElementById("previewTitleInput").value = downloadBooks.mainFileName
            document.getElementById("previewImageUrl").textContent = downloadBooks.imageUrl;
            document.getElementById("previewBeginPage").textContent = downloadBooks.beginPage;
            document.getElementById("previewEndPage").textContent = downloadBooks.endPage;
            document.getElementById("previewPictureType").textContent = downloadBooks.pictureType.join(", ");
            // 设置封面图片（检查图片类型数组是否为空）
            if (downloadBooks.pictureType && downloadBooks.pictureType.length > 0) {
                document.getElementById("previewCover").src = downloadBooks.imageUrl + downloadBooks.beginPage + downloadBooks.pictureType[0];
            } else {
                // 如果没有图片类型，设置默认图片或隐藏图片
                document.getElementById("previewCover").style.display = "none";
            }
            // Step3: 显示模态框
            const previewModal = new bootstrap.Modal(document.getElementById('previewModal'));
            previewModal.show();

            // Step4: 用户确认后触发下载
            document.getElementById("confirmDownloadBtn").onclick = async () => {
                // 从输入框获取编辑后的书名
                downloadBooks.mainFileName = document.getElementById("previewTitleInput").value.trim() || downloadBooks.mainFileName;
                previewModal.hide(); // 隐藏弹框
                logMessage("开始下载"+ downloadBooks.imageUrl+"...");

                try {
                    let downloadResp = await axios.post("/api/download", downloadBooks, {
                        onDownloadProgress: (progressEvent) => {
                            if (progressEvent.lengthComputable) {
                                let percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
                                updateProgress(percent);
                            }
                        }
                    });
                    logMessage("下载完成！"+ downloadBooks.imageUrl);
                    updateProgress(100);
                } catch (e) {
                    console.error(e);
                    logMessage("❌ 下载失败: " + e);
                }
            };

        } catch (e) {
            console.error(e);
            logMessage("❌ 下载失败: " + e);
        }
    });
</script>
</body>
</html>
